<template>
    <section>
        <full-screen-dialog
            title="发送对账申请"
            v-model="visible"
            :width="1500"
            destroy-on-close
            @closed="$emit('closed')"
        >
            <el-form ref="dialogForm" label-width="100px">
                <el-form inline label-width="49px" :model="entityObj" style="margin-top: 5px">
                    <el-form-item label="对账时间" label-width="100px">
                        <el-date-picker
                            @change="changeAccountDate"
                            style="width: 300px"
                            v-model="entityObj.accountDate"
                            type="datetimerange"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss"
                            range-separator="-"
                            unlink-panels="true"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :default-time="defaultTime"
                        />
                    </el-form-item>
                    <el-form-item label="客户名称" label-width="100px">
                        <sc-apply-org-select
                            ref="orgselect"
                            queryType="purchase-unity-store-relation/pages"
                            :props="storeProps"
                            :selectKeyValue="'storeId'"
                            v-model="entityObj.store"
                            :multiple="false"
                            @fatherMethod="orgSelectProcess"
                            style="width: 100%;"
                        ></sc-apply-org-select>
                    </el-form-item>
                    <br />
                    <el-form-item label="申请人" label-width="100px">
                        <el-input
                            placeholder="---请输入申请人---"
                            v-model="entityObj.ApplicantUser"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="联系电话" label-width="100px">
                        <el-input
                            placeholder="---请输入联系电话---"
                            v-model="entityObj.Tel"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <br />
                    <el-form-item label-width="100px" label="附件上传">
                        <sc-upload-file
                            v-model="entityObj.accountFile"
                            :objName="'Supply/giveOrder'"
                            draggable
                            :uploadType="'OSS'"
                            :bucketName="'jtmc'"
                            :limit="1"
                        />
                    </el-form-item>
                    <br />
                    <el-form-item label="备注" label-width="100px">
                        <el-input
                            placeholder="---请输入一些对账的要求---"
                            v-model="entityObj.Remarks"
                            type="textarea"
                            style="width: 300px"
                        />
                    </el-form-item>
                </el-form>
                <div style="margin-bottom: 10px;">
                    <el-button type="primary" @click="opDelBatch()">批量删除</el-button>
                    <el-button type="primary" @click="openBIgTable()">请选择对账数据</el-button>
                </div>

                <!--  :span-method="objectSpanMethod" show-summary -->
                <el-table
                    ref="mytable"
                    show-summary
                    :data="entityObj.items"
                    :border="true"
                    @selection-change="selectionChange"
                    :row-class-name="setRowClass"
                    style="width: 100%"
                >
                    <el-table-column type="selection" width="50"></el-table-column>
                    <el-table-column label="序号" type="index" width="80"></el-table-column>
                    <el-table-column label="业务日期" width="200" prop="applyDate"></el-table-column>
                    <el-table-column label="单据编号" width="200" prop="orderCode"></el-table-column>
                    <el-table-column label="客户" width="250" prop="storeName"></el-table-column>
                    <el-table-column label="制单人" width="200" prop="documentsUser"></el-table-column>
                    <el-table-column label="类型" width="150">
                        <template #default="scope">
                            {{scope.row.receivingOrderType=='0'?'要货订单':''}}
                            {{scope.row.receivingOrderType=='1'?'退货订单':''}}
                            {{scope.row.receivingOrderType=='2'?'空瓶订单':''}}
                            {{scope.row.receivingOrderType=='3'?'赠送订单':''}}
                        </template>
                        <!-- <template #default="scope">
							{{scope.row.receivingOrderType=='0'?'销售出库单':''}}
							{{scope.row.receivingOrderType=='1'?'销售退货单':''}}
							{{scope.row.receivingOrderType=='2'?'销售回瓶单':''}}
							{{scope.row.receivingOrderType=='3'?'销售赠送单':''}}
                        </template>-->
                    </el-table-column>
                    <!-- <el-table-column label="业务员" width="200" prop="salesman"></el-table-column> -->

                    <el-table-column label="关联订单编号" width="200" prop="applyOrderCode">
                        <template #default="scope">
                            {{scope.row.receivingOrderType==0?scope.row.applyOrderCode:''}}
                            {{scope.row.receivingOrderType==1?scope.row.afterOrderCode:''}}
                            {{scope.row.receivingOrderType==2?scope.row.recoveryCode:''}}
                            {{scope.row.receivingOrderType==3?scope.row.giveOrderCode:''}}
                        </template>
                    </el-table-column>
                    <el-table-column label="物料编码" width="200" prop="materialCode"></el-table-column>
                    <el-table-column label="物料名称" width="200" prop="materialName"></el-table-column>
                    <el-table-column label="规格型号" width="200" prop="materialSpecs"></el-table-column>
                    <el-table-column label="单位" width="100" prop="unitName"></el-table-column>
                    <el-table-column label="结算数量" prop="qty" width="150"></el-table-column>
                    <!-- <el-table-column label="配送数量" prop="deliveryQty" width="150"></el-table-column> -->
                    <!-- <el-table-column label="差异" width="100" prop="lackQty"></el-table-column> -->
                    <el-table-column label="结算价" width="100" prop="price"></el-table-column>
                    <!-- <el-table-column label="要货单价" width="150" prop="applyPrice"></el-table-column>
                    <el-table-column label="差异" width="100" prop="lackPrice"></el-table-column>-->
                    <el-table-column label="金额" width="100" prop="totalAmount"></el-table-column>
                    <el-table-column label="对账状态" prop="reconciliationStatusName" width="150">
                        <template #default="scope">
                            {{scope.row.reconciliationStatus=='1'?'已对账':''}}
                            {{scope.row.reconciliationStatus=='2'?'未对账':''}}
                            {{scope.row.reconciliationStatus=='3'?'对账中':''}}
                            {{scope.row.reconciliationStatus=='4'?'已发送申请':''}}
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" prop="remarks" width="150"></el-table-column>
                    <el-table-column label="操作" fixed="right" align="right" width="120">
                        <template #default="scope">
                            <el-button-group>
                                <el-button
                                    text
                                    type="primary"
                                    size="small"
                                    @click="opDel(scope.row, scope.$index)"
                                >删除</el-button>
                                <el-button
                                    text
                                    type="primary"
                                    size="small"
                                    @click="opCheck(scope.row, scope.$index)"
                                >核对</el-button>
                            </el-button-group>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>

            <template #footer>
                <div style="text-align: center;">
                    <el-button @click="visible = false">关 闭</el-button>
                    <el-button type="primary" @click="submitSave()">确认发送对账申请至门店</el-button>
                </div>
            </template>
        </full-screen-dialog>

        <!-- 选择出库单 list -->
        <receive-big
            v-if="visibleBig"
            ref="visibleBig"
            @fatherMethod="opBindData"
            @checkTable="checkTable"
            @success="handleSaveSuccess"
            @closed="visibleBig = false"
        ></receive-big>

        <!-- 核对弹窗 -->
        <check-dialog
            v-if="dialogCheck"
            ref="checkDialog"
            @fatherMethod="opBindData"
            @success="handleSaveSuccess"
            @closed="dialogCheck = false"
        ></check-dialog>

        <!--未对账弹窗-->
        <el-dialog title="提示" width="1200px" v-model="unCheckDialog">
            <div
                style="font-size: 16px;text-align: center;color: red;margin: 10px;"
            >{{unCheckDialogTip}}</div>
            <el-date-picker
                style="width: 300px"
                v-model="unCheckQuery.applyDate"
                type="datetimerange"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                range-separator="-"
                unlink-panels="true"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :default-time="defaultTime"
            />&nbsp;
            <el-input
                placeholder="---请输入物料编码---"
                v-model="unCheckQuery.materialCode"
                style="width: 180px"
            />&nbsp;
            <el-input
                placeholder="---请输入物料名称---"
                v-model="unCheckQuery.materialName"
                style="width: 180px"
            />&nbsp;
            <el-button type="primary" @click="unCheckSeach">查询</el-button>
            <el-table
                :data="unCheckItemResults"
                style="width: 100%"
                max-height="450"
                @selection-change="unCheckSelectionChange"
            >
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column label="业务日期" width="200" prop="applyDate"></el-table-column>
                <el-table-column label="单据编号" width="200" prop="orderCode"></el-table-column>
                <el-table-column label="客户" width="250" prop="storeName"></el-table-column>
                <el-table-column label="制单人" width="200" prop="documentsUser"></el-table-column>
                <el-table-column label="类型" width="150">
                    <template #default="scope">
                        {{scope.row.receivingOrderType=='0'?'要货订单':''}}
                        {{scope.row.receivingOrderType=='1'?'退货订单':''}}
                        {{scope.row.receivingOrderType=='2'?'空瓶订单':''}}
                        {{scope.row.receivingOrderType=='3'?'赠送订单':''}}
                    </template>
                </el-table-column>
                <el-table-column label="关联订单编号" width="200" prop="applyOrderCode">
                    <template #default="scope">
                        {{scope.row.receivingOrderType==0?scope.row.applyOrderCode:''}}
                        {{scope.row.receivingOrderType==1?scope.row.afterOrderCode:''}}
                        {{scope.row.receivingOrderType==2?scope.row.recoveryCode:''}}
                        {{scope.row.receivingOrderType==3?scope.row.giveOrderCode:''}}
                    </template>
                </el-table-column>
                <el-table-column label="物料编码" width="200" prop="materialCode"></el-table-column>
                <el-table-column label="物料名称" width="200" prop="materialName"></el-table-column>
                <el-table-column label="规格型号" width="200" prop="materialSpecs"></el-table-column>
                <el-table-column label="单位" width="100" prop="unitName"></el-table-column>
                <el-table-column label="结算数量" prop="qty" width="150"></el-table-column>
                <el-table-column label="结算价" width="100" prop="price"></el-table-column>
                <el-table-column label="金额" width="100" prop="totalAmount"></el-table-column>
                <el-table-column label="对账状态" prop="reconciliationStatusName" width="150">
                    <template #default="scope">
                        {{scope.row.reconciliationStatus=='1'?'已对账':''}}
                        {{scope.row.reconciliationStatus=='2'?'未对账':''}}
                        {{scope.row.reconciliationStatus=='3'?'对账中':''}}
                        {{scope.row.reconciliationStatus=='4'?'已发送申请':''}}
                    </template>
                </el-table-column>
                <el-table-column label="备注" prop="remarks" width="150"></el-table-column>
            </el-table>
            <template #footer>
                <div style="text-align: center;">
                    <el-button @click="unCheckDialog = false">取消</el-button>
                    <el-button type="primary" @click="unCheckAdd()">确定添加</el-button>
                    <el-button type="warning" @click="confirmSendAccountData()">发送账单</el-button>
                </div>
            </template>
        </el-dialog>
    </section>
</template>

<script>
import checkDialog from "./check";
import receiveBig from "./receiveBig";
import tool from "@/utils/tool";
export default {
    components: {
        receiveBig,
        checkDialog,
    },
    emits: ["success", "closed"],
    data() {
        return {
            firstIndex: 0,
            storeProps: {
                label: "storeOrgName",
                value: "storeId",
            },
            dialogCheck: false,
            visibleBig: false,
            visible: false,
            selectionRows: [],
            // 发送请求的实体modal
            entityObj: {
                salesAccountID: 0,
                storeId: "",
                accountFile: "",
                accountDate: [],
                items: [],
                store: "",
            },
            unCheckDialog: false, //未对账弹窗
            unCheckDialogTip: "", //未对账提示
            unCheckItems: [], //未对账数据
			unCheckItemResults:[],//未对账查询后数据
            unCheckSelectionRows: [],
            defaultTime: [
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ],
            unCheckQuery: {},
        };
    },
    methods: {
        // 选中后返回的选中数据
        checkTable(emitData) {
            this.entityObj.items = emitData;
            // this.$nextTick(() => {
            // 	this.$refs.mytable.toggleAllSelection();
            // });
        },
        // 批量删除 - 前端自行操作
        opDelBatch() {
            if (this.selectionRows.length > 0) {
                this.selectionRows.forEach((row) => {
                    this.entityObj.items.splice(
                        this.entityObj.items.indexOf(row),
                        1
                    );
                });
            } else {
                this.$message.error("请选择要删除的数据");
            }
        },
        // 弹窗 对物料的信息进行调整  - 前端自行操作
        opCheck(checkRow, index) {
            this.dialogCheck = true;
            this.$nextTick(() => {
                console.log("opCheck", checkRow);
                this.$refs.checkDialog.setData(checkRow);
                this.$refs.checkDialog.open("Check");
            });
        },
        // 单条删除 - 前端自行操作
        opDel(row, index) {
            this.entityObj.items.splice(index, 1);
            // 以下是移除全部相关数据
            // let items = this.entityObj.items;
            // let filteredItems = items.filter( (item) => item.receivingOrderId !== row.receivingOrderId );
            // this.entityObj.items = filteredItems;
        },
        async orgSelectProcess(rowData) {
            this.entityObj.store = {
                storeOrgType:rowData.storeOrgType,
                storeId: rowData.storeId,
                storeOrgName: rowData.storeOrgName,
            };
            this.entityObj.storeOrgType = rowData.storeOrgType;
            this.entityObj.storeId = rowData.storeId; 
        },
        async changeAccountDate(changgedate) {
            console.log(changgedate);
            this.entityObj.items = [];
        },
        openBIgTable() {
            if (
                !this.entityObj.accountDate ||
                this.entityObj.accountDate.length == 0
            ) {
                this.$message.error("请选择对账时间");
                return;
            }
            if (!this.entityObj.storeId) {
                this.$message.error("请选择客户");
                return;
            }
            this.visibleBig = true;
            this.$nextTick(() => {
                console.log("opBigTable", this.entityObj.items);
                this.$refs.visibleBig.initData(
                    this.entityObj.items,
                    this.entityObj.storeId,
                    this.entityObj.accountDate,
                    this.entityObj.storeOrgType,
                );
            });
        },
        open() {
            this.visible = true;
            this.entityObj.items = [];
            this.entityObj.ApplicantUser = tool.data.get("USER_INFO").Name;
            this.entityObj.Tel = tool.data.get("USER_INFO").Mobile;
        },
        async submitSave() {
            if (!this.entityObj.accountDate) {
                this.$message.error("请选择对账时间");
                return;
            }
            if (!this.entityObj.storeId) {
                this.$message.error("请选择客户");
                return;
            }
            if (!this.entityObj.items.length > 0) {
                this.$message.error("请选择出库单");
                return;
            }
            try {
                var lastresponse = await this.$API.auth.PostProcessApi.post(
                    "receiving-order/islastaccount",
                    this.entityObj
                );
                if (lastresponse.status == 200) {
                    if (!lastresponse.response.success) {
                        this.unCheckDialog = true;
                        this.unCheckDialogTip =
                            lastresponse.response.msg + ",是否继续?";
                        this.unCheckItems = lastresponse.response.unChecks;
						this.unCheckSeach();
                        // this.$confirm(lastresponse.response.msg + ',是否继续?', '提示', {
                        // 	confirmButtonText: '确定',
                        // 	cancelButtonText: '取消',
                        // 	type: 'warning'
                        // }).then(async () => {
                        // 	// console.log('发生至门店modal：',this.entityObj)
                        // 	const returnValue = await this.$API.auth.PostProcessApi.post(
                        // 		"receiving-order/saleaccount",
                        // 		this.entityObj
                        // 	);
                        // 	if (returnValue.status == 200) {
                        // 		this.$message.success(returnValue.msg);
                        // 		this.$emit("success");
                        // 		this.visible = false;
                        // 	} else {
                        // 		this.$message.error("操作失败:" + returnValue.msg);
                        // 	}
                        // });
                    } else {
                        const returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                "receiving-order/saleaccount",
                                this.entityObj
                            );
                        if (returnValue.status == 200) {
                            this.$message.success(returnValue.msg);
                            this.$emit("success");
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                        }
                    }
                } else {
                    this.$message.error("操作失败:" + lastresponse.msg);
                }
            } catch (error) {
                this.loading = false;
                this.$message.error(error.message);
                return false;
            }
        },
		//未对账查询
		unCheckSeach(){
			this.unCheckItemResults=this.unCheckItems;
			if (this.unCheckQuery.applyDate) {
				console.log('applyDate',this.unCheckQuery.applyDate)
				this.unCheckItemResults = this.unCheckItemResults.filter(p=>p.applyDate>=this.unCheckQuery.applyDate[0]&&p.applyDate<=this.unCheckQuery.applyDate[1]);
            }

			if (this.unCheckQuery.materialCode) {
				this.unCheckItemResults = this.unCheckItemResults.filter(p=>p.materialCode.includes(this.unCheckQuery.materialCode));
            }

			if (this.unCheckQuery.materialName) {
				this.unCheckItemResults = this.unCheckItemResults.filter(p=>p.materialName.includes(this.unCheckQuery.materialName));
            }
		},
        //确定发送对账数据
        async confirmSendAccountData() {
            console.log("发生至门店modal：", this.entityObj);
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "receiving-order/saleaccount",
                this.entityObj
            );
            if (returnValue.status == 200) {
                this.$message.success(returnValue.msg);
                this.$emit("success");
                this.visible = false;
            } else {
                this.$message.error("操作失败:" + returnValue.msg);
            }
        },
        //选择未对账数据添加
        async unCheckAdd() {
            if (this.unCheckSelectionRows.length > 0) {
                this.unCheckSelectionRows.forEach((row) => {
                    this.entityObj.items.push(row);
                });
                this.unCheckDialog = false;
            } else {
                this.$message.error("请选择要添加的数据");
            }
        },
        setRowClass({ row }) {
            if (this.selectionRows.includes(row)) {
                return "selected-row-color";
            }
            return "";
        },
        //表格选择后回调事件
        selectionChange(selection) {
            this.selectionRows = selection;
        },
        unCheckSelectionChange(selection) {
            this.unCheckSelectionRows = selection;
        },
        // 合并列
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            // 用于标志合并列的第一行
            // 初始化firstIndex
            if (rowIndex == 0 && columnIndex == 0) {
                this.firstIndex = 0;
            }
            // 当前行占用行数
            const zyRow = row.receivingOrderItems.length;

            // 对于合并列 如果当前行索引==firstIndex
            if (columnIndex == 0 || columnIndex == 17) {
                // 合并列的第一行 占用行数=zyRow 列数=1
                if (rowIndex == this.firstIndex) {
                    // 计算合并列的第一行 计算时机为处理到合并列第一行的最后一列
                    if (rowIndex == this.firstIndex && columnIndex == 17) {
                        this.firstIndex = this.firstIndex + zyRow;
                    }
                    return {
                        rowspan: zyRow,
                        colspan: 1,
                    };
                }
                // 合并列的剩余行，不占用行数和列数
                else {
                    return {
                        rowspan: 0,
                        colspan: 0,
                    };
                }
            }
            // 非合并列 都占用一行一列
            else {
                // 计算合并列的第一行 计算时机为处理到合并列第一行的最后一列
                if (rowIndex == this.firstIndex && columnIndex == 17) {
                    this.firstIndex = this.firstIndex + zyRow;
                }
                return {
                    rowspan: 1,
                    colspan: 1,
                };
            }
        },
    },
};
</script>

<style lang="scss" scoped>
/* 当表格行处于悬停状态时改变背景颜色 */
::v-deep .el-table .el-table__row:hover {
    background-color: #dae8f7;
}
::v-deep .el-table__body .el-table__row--striped.hover-row td {
    background-color: #dae8f7 !important;
}
//   斑马纹选中颜色
::v-deep .el-table__body .el-table__row--striped.selected-row-color td {
    background-color: #b8dcff !important;
}
::v-deep .el-table {
    --el-table-row-hover-bg-color: #dae8f7;
}

::v-deep .el-table tr:nth-child(2n) {
    background: #f2f2f2;
}
</style>
<style>
.el-table .selected-row-color {
    background-color: #b8dcff !important;
}
.el-table--enable-row-hover .el-table__body tr.selected-row-color:hover > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper .el-table__body tr.selected-row-color.hover-row > td {
    background-color: #b8dcff !important;
}
.el-table__fixed-body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > .el-table__row--striped {
    background-color: #b8dcff !important;
}
</style>




